<template>
  <div class="dataTable">
    <div class="search_area">
      <el-form ref="searchForm" :inline="true" :model="searchForm">
        <el-form-item prop="report_account">
          <el-input v-model="searchForm.report_account" placeholder="输入汇报人查询" @keyup.enter.native="onSearch" />
        </el-form-item>
        <el-form-item prop="review_account">
          <el-input v-model="searchForm.review_account" placeholder="输入点评人查询" @keyup.enter.native="onSearch" />
        </el-form-item>
        <el-form-item prop="stat">
          <el-select v-model="searchForm.stat" placeholder="全部（点评状态）" @keyup.enter.native="onSearch">
            <el-option label="全部（点评状态）" value="" />
            <el-option label="已点评" :value="1" />
            <el-option label="未点评" :value="2" />
          </el-select>
        </el-form-item><br>
        <el-form-item prop="filter_time">
          <el-date-picker
            v-model="searchForm.filter_time"
            type="daterange"
            align="right"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="onSearch">查询</el-button>
          <el-button plain style="margin-right: 20px;" :loading="loading" @click="resetForm('searchForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_area">
      <div style="font-size: 12px">
        已分配人：
        <span v-for="(item, index) in groupItem.group_accounts ? groupItem.group_accounts : []" :key="index">
          {{ `${item.account_info.real_name}${index === groupItem.group_accounts.length - 1 ? '' : ','}` }}
        </span>
      </div>
      <div v-if="!noPermissionYet">
        <el-table
          v-loading="loading"
          :data="dataList"
          style="width: 100%"
          @selection-change="selectionChange"
        >
          <!-- 在回收站没有收藏 -->
          <el-table-column
            v-if="!groupItem['del']"
            :key="Math.random()"
            align="center"
            prop="status"
            label="收藏报告"
            width="120"
          >
            <div slot-scope="{row}">
              <div :class="row.is_star === 1 ? 'isStar_icon' : 'unStar_icon'" @click="setStar(row)" />
            </div>
          </el-table-column>

          <!-- 回收站批量删除 -->
          <el-table-column
            v-else
            :key="Math.random()"
            type="selection"
            width="120"
          />

          <el-table-column
            prop="group.name"
            label="报告分组"
            width="250"
          />
          <el-table-column
            prop="created_rel_name"
            label="汇报人"
            width="150"
          >
            <div slot-scope="{row}">{{ row.created_rel_name ? row.created_rel_name : '--' }}</div>
          </el-table-column>
          <el-table-column
            prop="count"
            label="点评人"
            width="150"
          >
            <div slot-scope="{row}">{{ row.review ? row.review.reviewaccount.real_name : '--' }}</div>
          </el-table-column>
          <el-table-column
            prop="status"
            label="点评状态"
            width="150"
          >
            <div slot-scope="{row}">
              <div :class="row.status === 1 ? 'sucess_point' : 'fail_point'" />{{ row.status === 1 ? '已点评' : '未点评' }}
            </div>
          </el-table-column>
          <el-table-column
            prop="review.score"
            label="点评分数"
            width="150"
          >
            <div slot-scope="{row}">{{ row.review ? (row.review.score || '--' ) : '--' }}</div>
          </el-table-column>
          <el-table-column
            prop="modify_time"
            label="更新时间"
            width="280"
          />
          <el-table-column
            prop="operate"
            label="操作"
            width="220"
          >
            <div slot-scope="{row, $index}" style="display: flex;">
              <el-tooltip effect="dark" :content="myInfo.role_id === 100003 || groupItem['del'] || groupItem['star'] ? '查看' : '点评'" placement="top">
                <div class="check_icon" @click="$parent.moudleChange(false, row,dataList.length === $index + 1, reqParams, groupItem['del'] || groupItem['star'] ? true : undefined )" />
              </el-tooltip>
              <el-tooltip effect="dark" content="恢复" placement="top">
                <div v-show="groupItem['del']" class="move_icon" @click="move(row)" />
              </el-tooltip>
              <!-- 在报告页面的删除 -->
              <el-tooltip effect="dark" content="删除" placement="top">
                <div v-show="!groupItem['del'] && !groupItem['star']" class="delete_icon" @click="remove(row)" />
              </el-tooltip>
              <!-- 在回收站的删除 -->
              <el-tooltip effect="dark" content="删除" placement="top">
                <div v-show="groupItem['del']" class="delete_icon" @click="handleDelete(row)" />
              </el-tooltip>
            </div>
          </el-table-column>
        </el-table>

        <div class="pager_area my-flex">
          <div class="my-flex">
            <!-- 如果是收藏页面 && 当分组存在二级“文件夹”，隐藏“全部移除”按钮 -->
            <div
              v-show="'star' in groupItem === false && 'child' in groupItem === false"
              class="batch_btn"
              @click="batchDelete()"
            >
              <div class="batch_delete" />
              <!-- 在普通报告页面显示 全部删除 ，在回收站页面显示 批量删除 -->
              <div class="text">{{ groupItem['del'] === 1 ? '批量删除' : '全部移除' }}</div>
            </div>
          </div>
          <el-pagination
            :current-page="pager.page"
            :page-sizes="pager.pageSizes"
            :page-size="pager.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pager.total"
            @size-change="pageSizeChange"
            @current-change="pageChange"
          />
        </div>
      </div>
      <div v-else>
        <div class="noPermissionYet_icon" />
        <div class="noPermissionYet_text">暂无权限</div>
      </div>
    </div>

    <moveDialog :visible="move_visible" :check-data="checkData" @close="closeMoveDialog" @updateFolder="$emit('updateFolder','del')" />
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { report_list, report_delete, report_setstar } from '@/api/report'
import moveDialog from './move-dialog.vue'

export default {
  name: 'DataTable',
  components: { moveDialog },
  props: {
    groupId: {
      type: Number,
      default: 0
    },
    groupItem: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    // 这里存放数据
    return {
      loading: false,
      dataList: [],
      searchForm: {
        filter_time: '',
        stat: '',
        report_account: '',
        review_account: ''
      },
      pager: {
        page: 1,
        pageSizes: [5, 10, 20],
        pageSize: 10,
        total: 0
      },
      checkData: {},
      reqParams: {},
      move_visible: false,
      noPermissionYet: true,
      selectionedList: [] // 回收站批量删除数组
    }
  },
  computed: {
    ...mapState({
      myInfo: (state) => state.basicSettings.myInfo
    })
  },
  // 监控data中的数据变化
  watch: {
    groupItem(n, o) {
      this.checkPermission()
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created() { },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.checkPermission()
  },
  // 生命周期 - keep-alive
  async activated() { },
  // 方法集合
  methods: {
    // 回收站批量删除
    selectionChange(val) {
      this.selectionedList = val
    },
    // 批量删除
    batchDelete() {
      // 因为普通的列表，回收站，收藏夹都在同一个页面，所以需要做逻辑
      const { groupItem } = this
      let result
      for (const key in groupItem) {
        if (key === 'del' || key === 'star') {
          result = key
          break
        }
      }

      switch (result) {
        case 'del':
          // 走删除回收站逻辑
          this.batchDeleteTrash()
          break

        case 'star':
          // 走删除收藏逻辑
          break

        default:
          // 走普通删除全部逻辑
          this.batchDeleteReport()
          break
      }
    },
    // 回收站，单个删除
    handleDelete(data) {
      // 构造postData
      const tip = '此操作将删除所选报告, 是否继续?'
      const id = '-1' // -1 并没有实际作用，只是不能为空
      const deleteIds = [data.id] // 需要删除的id
      const postData = {
        ac: 'destroy',
        deleteIds
      }

      // 回调
      const callbackFn = () => {
        // 删除完成需要更新左侧栏
        this.$emit('updateFolder', 'del')
      }

      // 发送请求,还是调用批量删除接口
      this.batchDeleteRequest(tip, id, postData, callbackFn)
    },
    // 批量删除报告，也就说删除整个文件夹下的报告
    batchDeleteReport() {
      const tip = '此操作将把报告全部移入回收站, 是否继续?'
      const { id } = this.groupItem// 文件夹id
      const postData = {
        ac: 'delall'
      }
      const callbackFn = () => {
        // 删除完成需要更新左侧栏
        this.$emit('updateFolder', 'report')
      }

      // 发送请求
      this.batchDeleteRequest(tip, id, postData, callbackFn)
    },
    // 批量删除回收站内容
    batchDeleteTrash() {
      // 判断是否选择
      const { selectionedList } = this
      const { length } = selectionedList
      if (length === 0) {
        this.$messageOnce.warning('暂无选中报告')
        return false
      }

      // 获取Id
      const deleteIds = []
      selectionedList.forEach(element => {
        deleteIds.push(element.id)
      })

      // 构造postData
      const tip = '此操作将删除所选报告, 是否继续?'
      const id = '-1' // -1 并没有实际作用，只是不能为空
      const postData = {
        ac: 'destroy',
        deleteIds
      }

      // 回调
      const callbackFn = () => {
        // 删除完成需要更新左侧栏
        this.$emit('updateFolder', 'del')
      }

      // 发送请求
      this.batchDeleteRequest(tip, id, postData, callbackFn)
    },
    // 批量删除请求
    batchDeleteRequest(tip, id, postData, callbackFn) {
      // 先判断是否有内容，没有则弹出提示
      const { length } = this.dataList
      if (length === 0) {
        this.$messageOnce.warning('暂无数据')
        return false
      }

      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.loading = true
        try {
          const { code } = await report_delete(id, postData)
          if (!code) {
            this.$messageOnce.success('操作成功！')
            this.loadData()
            callbackFn()
          }
        } catch (error) {
          console.error(error)
        } finally {
          this.loading = false
        }
      }).catch(() => { })
    },
    checkPermission() {
      // console.log('\b')
      // console.log('checkPermission')
      if (this.myInfo.role_id === 100000 || this.myInfo.role_id === 100003) {
        this.noPermissionYet = false
        this.loadData()
        return
      }
      // console.log('this.groupItem.group_accounts');
      // console.log(this.groupItem.group_accounts);
      const ownerAccount = this.findElement('account', this.groupItem.group_accounts)
      console.log(ownerAccount, this.myInfo.account)
      if (this.groupId && ownerAccount.length) { // 有被分配
        // console.log('设置需要权限')

        if (ownerAccount.indexOf(this.myInfo.account) !== -1) {
          this.noPermissionYet = false
          // console.log('375 loadData 有权限看这个文件')
          this.loadData()
        } else {
          // 没有权限看文件
          // console.log('没有权限看文件')
          this.noPermissionYet = true
        }
      } else {
        this.noPermissionYet = false
        // console.log('382 loadData 没有设置权限')
        this.loadData()
      }
    },
    async loadData() {
      this.loading = true
      try {
        const param = {
          page: this.pager.page,
          per_page: this.pager.pageSize,
          group: this.groupId || undefined,
          stat: this.searchForm.stat || undefined,
          del: this.groupItem['del'] ? 1 : 2, // del = 1 代表打开回收站
          star: this.groupItem['star'] ? 1 : undefined, // star = 1 代表打开收藏夹
          with: ['reportaccount', 'review.reviewaccount', 'group'],
          report_account: this.searchForm.report_account || undefined,
          review_account: this.searchForm.review_account || undefined,
          start_time: this.searchForm.filter_time ? this.searchForm.filter_time[0] : undefined,
          end_time: this.searchForm.filter_time ? this.searchForm.filter_time[1] : undefined,
          ltype: '1' // 说明：1：Solidity2：golang 3:linux
        }
        this.reqParams = param
        const { code, data } = await report_list(param)
        if (!code) {
          this.dataList = data.data
          const { pager } = this
          pager.page = data.current_page
          pager.total = data.total
          pager.pageSize = Number(data.per_page)
        }
        this.loading = false
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    async setStar(data) {
      try {
        this.loading = true
        const { code } = await report_setstar(data.id, { is_star: data.is_star === 1 ? 2 : 1 })
        if (!code) {
          this.$messageOnce.success(data.is_star === 1 ? '取消收藏成功' : '设置收藏成功')
          this.loadData()
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    remove(data) {
      this.$confirm('此操作将把该报告移入回收站, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.loading = true
        try {
          const { code } = await report_delete(data.id, { ac: 'del' })
          if (!code) {
            this.$messageOnce.success('操作成功！')
            this.loadData()
            // 删除完成需要更新左侧栏
            this.$emit('updateFolder', 'report')
          }
        } catch (error) {
          console.error(error)
        } finally {
          this.loading = false
        }
      }).catch(() => { })
    },

    move(data) {
      this.move_visible = true
      this.checkData = data
    },
    closeMoveDialog() {
      this.move_visible = false
    },
    onSearch() {
      const { pager } = this
      pager.page = 1
      this.loadData()
    },
    pageSizeChange(val) {
      const { pager } = this
      pager.pageSize = val
      this.loadData()
    },
    pageChange(val) {
      const { pager } = this
      pager.page = val
      this.loadData()
    },
    resetForm() {
      this.$refs.searchForm.resetFields()
      this.loadData()
    },
    findElement(element, array) {
      if (!array || !element) {
        return []
      }
      const arr = []
      for (let i = 0; i < array.length; i++) {
        const item = array[i]
        arr.push(item[element])
      }
      return arr
    }
  },
  // 进入页面前
  beforeRouteEnter(to, from, next) {
    next(vm => {

    })
  },
  // 离开页面前
  beforeRouteLeave(to, from, next) {
    next()
  }
}
</script>
<style lang="scss" scoped>
 @import "~@/styles/mixin.scss";

.dataTable{
	width: 1540px;
	margin: 40px 30px;
	background-color: #FFFFFF;
	border-radius: 8px;
  .search_area {
    padding: 40px 30px 0 30px;
    border-bottom: 1px solid #E4E4E4;
  }
  .table_area {
    padding: 40px 30px;
  }
}

.sucess_point{
  @include points;
  display: inline-block;
  background: #52C41A;
}

.fail_point{
  @include points;
	display: inline-block;
  background: #999999;
}

.check_icon{
	background: url('../../assets/check@list.png');
  @include list_icons;
  width: 33px;
}

.move_icon{
  background: url('../../assets/move@list.png');
  @include list_icons;
}

.delete_icon{
  background: url('../../assets/delete@list.png');
  @include list_icons;
}

.isStar_icon{
  width: 22px;
  height: 20px;
  background: url('../../assets/report/is_star.png');
  background-size: 100%;
  margin: 0 auto;
  cursor: pointer;
}

.unStar_icon{
  width: 22px;
  height: 20px;
  background: url('../../assets/report/un_star.png');
  background-size: 100%;
  margin: 0 auto;
  cursor: pointer;
}

.noPermissionYet_icon {
  width: 280px;
  height: 202px;
  background: url('../../assets/noPermissionYet.png');
  background-size: 100%;
  margin: 30px auto;
}

.noPermissionYet_text {
  text-align: center;
  height: 16px;
  font-size: 16px;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  font-weight: 500;
  color: #999999;
  line-height: 16px;
}
.my-flex{
	display: flex;
	align-content: center;
	justify-content: space-between;
}

.pager_area {
  margin-top: 40px;

  .batch_btn {
    width: 100px;
    height: 28px;
    background: #F7F7F7;
    border-radius: 4px;
    border: 1px solid #2C2C2C;
    display: flex;
    padding: 5px 8px;
    margin-right: 20px;
    color: #2C2C2C;
    cursor: pointer;
    .text{
      height: 14px;
      font-size: 14px;
      font-family: SourceHanSansCN-Regular, SourceHanSansCN;
      font-weight: 400;
      margin-left: 7px;
    }
    &:hover{
      width: 100px;
      height: 28px;
      border-radius: 4px;
      background: #FFFFFF;
      border: 1px solid $MainColor;
      display: flex;
      padding: 5px 8px;
      margin-right: 20px;
      color: $MainColor;
      cursor: pointer;
      .batch_delete {
        width: 16px;
        height: 15px;
        background: url('../../assets/material/batch_delete_active.png');
        background-size: 100%;
      }
    }
  }

  .batch_delete {
    width: 16px;
    height: 15px;
    background: url('../../assets/material/batch_delete.png');
    background-size: 100%;
  }
}

::v-deep .el-form-item{
  margin-bottom: 30px;
  width: 260px;
}

::v-deep .el-form--inline .el-form-item {
    display: inline-block;
    margin-right: 30px;
    vertical-align: top;
}

::v-deep .el-form--inline .el-form-item__content {
    display: inline-block;
    vertical-align: top;
    width: 100%;
}

::v-deep .el-date-editor--daterange.el-input__inner {
    width: 260px;
}

::v-deep .el-select {
    display: inline-block;
    position: relative;
    width: 100%;
}
::v-deep .el-input__inner {
  &::placeholder {
    color: rgba(0, 0, 0, 0.5); // 0.8
  }
}

</style>
